package com.ruoyi.appointments.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestParam;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.appointments.domain.Appointments;
import com.ruoyi.appointments.service.IAppointmentsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.aliyun.tea.TeaException;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponseBody;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 预约信息Controller
 *
 * @author ruoyi
 * @date 2025-07-02
 */
@RestController
@RequestMapping("/appointments/appointments")
public class AppointmentsController extends BaseController
{
    @Autowired
    private IAppointmentsService appointmentsService;

    /**
     * 公开API - 提交预约信息
     */
    @PostMapping("/submit")
    public AjaxResult submitAppointment(
            @RequestParam(value = "name", required = true) String name,
            @RequestParam(value = "idCardNumber", required = true) String idCardNumber,
            @RequestParam(value = "gender", required = true) String gender,
            @RequestParam(value = "birthDate", required = true) String birthDateStr,
            @RequestParam(value = "ethnicity", required = true) String ethnicity,
            @RequestParam(value = "idCardAddress", required = true) String idCardAddress,
            @RequestParam(value = "province", required = true) String province,
            @RequestParam(value = "city", required = true) String city,
            @RequestParam(value = "district", required = true) String district,
            @RequestParam(value = "detailAddress", required = true) String detailAddress,
            @RequestParam(value = "phone", required = true) String phone,
            @RequestParam(value = "familyName1", required = true) String familyName1,
            @RequestParam(value = "familyPhone1", required = true) String familyPhone1,
            @RequestParam(value = "familyName2", required = false) String familyName2,
            @RequestParam(value = "familyPhone2", required = false) String familyPhone2,
            @RequestParam(value = "graduateProvince", required = true) String graduateProvince,
            @RequestParam(value = "graduateCity", required = true) String graduateCity,
            @RequestParam(value = "graduateDistrict", required = true) String graduateDistrict,
            @RequestParam(value = "graduateSchool", required = true) String graduateSchool,
            @RequestParam(value = "graduateStatus", required = true) String graduateStatus,
            @RequestParam(value = "examNumber", required = false) String examNumber,
            @RequestParam(value = "targetSchool", required = true) String targetSchool,
            @RequestParam(value = "majorDirection", required = true) String majorDirection,
            @RequestParam(value = "targetMajor", required = true) String targetMajor,
            @RequestParam(value = "idCardImage", required = false) MultipartFile idCardImage) {
        try {
            Appointments appointment = new Appointments();
            appointment.setName(name);
            appointment.setIdCardNumber(idCardNumber);
            appointment.setGender(gender);

            // 转换日期字符串为Date对象
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date birthDate = dateFormat.parse(birthDateStr);
            appointment.setBirthDate(birthDate);

            appointment.setEthnicity(ethnicity);
            appointment.setIdCardAddress(idCardAddress);
            appointment.setProvince(province);
            appointment.setCity(city);
            appointment.setDistrict(district);
            appointment.setDetailAddress(detailAddress);
            appointment.setPhone(phone);
            appointment.setFamilyName1(familyName1);
            appointment.setFamilyPhone1(familyPhone1);
            appointment.setFamilyName2(familyName2);
            appointment.setFamilyPhone2(familyPhone2);
            appointment.setGraduateProvince(graduateProvince);
            appointment.setGraduateCity(graduateCity);
            appointment.setGraduateDistrict(graduateDistrict);
            appointment.setGraduateSchool(graduateSchool);
            appointment.setGraduateStatus(graduateStatus);
            appointment.setExamNumber(examNumber);
            appointment.setTargetSchool(targetSchool);
            appointment.setMajorDirection(majorDirection);
            appointment.setTargetMajor(targetMajor);

            // 设置默认处理状态为"待处理"
            appointment.setStatus("待处理");

            // 上传身份证图片
            if (idCardImage != null && !idCardImage.isEmpty()) {
                try {
                    // 使用FileUploadUtils上传文件
                    // 上传到指定目录：/profile/upload/idcard
                    String idCardPath = RuoYiConfig.getUploadPath() + "/idcard";
                    // 使用正确的方法签名：upload(String baseDir, boolean isDatePath, MultipartFile file, String fileName)
                    String idCardImagePath = FileUploadUtils.upload(idCardPath, true, idCardImage, null);
                    appointment.setIdCardImagePath(idCardImagePath);
                } catch (Exception e) {
                    logger.error("身份证图片上传失败", e);
                    return AjaxResult.error("身份证图片上传失败：" + e.getMessage());
                }
            }

            // 设置创建时间和更新时间
            Date now = new Date();
            appointment.setCreatedAt(now);
            appointment.setUpdatedAt(now);

            // 保存预约信息
            appointmentsService.insertAppointments(appointment);

            return AjaxResult.success("预约信息提交成功，我们将尽快与您联系！", appointment.getId());
        } catch (Exception e) {
            logger.error("提交预约信息失败", e);
            return AjaxResult.error("提交预约信息失败：" + e.getMessage());
        }
    }

    /**
     * 查询预约信息列表
     */
    @PreAuthorize("@ss.hasPermi('appointments:appointments:list')")
    @GetMapping("/list")
    public TableDataInfo list(Appointments appointments)
    {
        startPage();
        List<Appointments> list = appointmentsService.selectAppointmentsList(appointments);
        return getDataTable(list);
    }

    /**
     * 导出预约信息列表
     */
    @PreAuthorize("@ss.hasPermi('appointments:appointments:export')")
    @Log(title = "预约信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Appointments appointments)
    {
        List<Appointments> list = appointmentsService.selectAppointmentsList(appointments);
        ExcelUtil<Appointments> util = new ExcelUtil<Appointments>(Appointments.class);
        util.exportExcel(response, list, "预约信息数据");
    }

    /**
     * 获取预约信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('appointments:appointments:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(appointmentsService.selectAppointmentsById(id));
    }

    /**
     * 新增预约信息
     */
    @PreAuthorize("@ss.hasPermi('appointments:appointments:add')")
    @Log(title = "预约信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Appointments appointments)
    {
        return toAjax(appointmentsService.insertAppointments(appointments));
    }

    /**
     * 修改预约信息
     */
    @PreAuthorize("@ss.hasPermi('appointments:appointments:edit')")
    @Log(title = "预约信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Appointments appointments)
    {
        return toAjax(appointmentsService.updateAppointments(appointments));
    }

    /**
     * 删除预约信息
     */
    @PreAuthorize("@ss.hasPermi('appointments:appointments:remove')")
    @Log(title = "预约信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(appointmentsService.deleteAppointmentsByIds(ids));
    }

    /**
     * 创建阿里云OCR客户端
     */
    public static com.aliyun.ocr_api20210707.Client createclient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                //您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        //访问的域名
        config.endpoint ="ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }
    /**
     * 身份证OCR识别接口
     */
    @PostMapping("/ocr")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public AjaxResult ocr(@RequestParam("file") MultipartFile file) {
        System.out.println("=== OCR接口被调用 ===");
        System.out.println("接收到的文件: " + (file != null ? file.getOriginalFilename() : "null"));
        System.out.println("文件大小: " + (file != null ? file.getSize() : "null"));

        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                System.err.println("文件为空或null");
                return AjaxResult.error("请上传身份证图片文件");
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return AjaxResult.error("请上传图片格式的身份证文件");
            }

            // 验证文件大小（限制5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return AjaxResult.error("图片文件大小不能超过5MB");
            }

            com.aliyun.ocr_api20210707.Client client = AppointmentsController.createclient(
                    "LTAI5tMEywvCWGGrYzbccc32",
                    "aSYgrDEBwj3piBdHBEjDNxznfrXz74"
            );

            java.io.InputStream bodyStream = file.getInputStream();

            com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest recognizeIdcardRequest = new com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest()
                    .setBody(bodyStream);

            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            RecognizeIdcardResponse response = client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);
            RecognizeIdcardResponseBody body = response.getBody();
            String result = body.data;

            return AjaxResult.success("身份证识别成功", result);

        } catch (TeaException error) {
            System.err.println("阿里云OCR识别错误: " + error.getMessage());
            if (error.getData() != null && error.getData().get("Recommend") != null) {
                System.err.println("建议: " + error.getData().get("Recommend"));
            }
            return AjaxResult.error("身份证识别失败: " + error.getMessage());
        } catch (Exception e) {
            System.err.println("OCR接口异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("身份证识别服务异常，请稍后重试");
        }
    }
}
